package ui;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import main.Common;
import main.Def;
import main.ExcelConvert;

public class Table extends JTable
{
	private static final long serialVersionUID = 1L;
	
	private DefaultTableModel m_model;
	
	public Table()
	{
		super();
		this.getTableHeader().setReorderingAllowed(false);
		m_model = new DefaultTableModel();
		this.setModel(m_model);
		m_model.addColumn("file");
		m_model.addColumn("config");
	}
	
	public void addFile()
	{
		JFileChooser chooser = new JFileChooser(Common.m_path);
		chooser.setLocation(MainWindow.instance().window().getLocation());
		chooser.setSize(MainWindow.instance().window().getSize());
		chooser.setMultiSelectionEnabled(true);
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int choice = chooser.showOpenDialog(MainWindow.instance().window());
		if(choice == JFileChooser.APPROVE_OPTION)
		{
			File[] selected = chooser.getSelectedFiles();
			for(File f: selected)
			{
				String name = f.getAbsolutePath();
				Object[] row = new Object[2];
				row[0] = name;
				row[1] = "";
				m_model.addRow(row);
			}
		}
	}
	
	public void remove()
	{
		int[] rows = this.getSelectedRows();
		for(int i = rows.length - 1; i >= 0; --i)
		{
			m_model.removeRow(rows[i]);
		}
	}
	
	public boolean isCellEditable(int row, int column)
	{
		return column == 1;
	}
	
	public String[] getSelectedWorkBooks()
	{
		int[] rows = this.getSelectedRows();
		String[] out = new String[rows.length];
		int index = 0;
		for(int i: rows)
		{
			out[index] = getValueAt(i, 0).toString();
			++index; 
		}
		return out;
	}
	
	public void run()
	{
		try
		{
			for(int i = 0, size = m_model.getRowCount(); i < size; ++i)
			{
				String name = getValueAt(i, 0).toString();
				String configSheet = getValueAt(i, 1).toString();
				if(configSheet.length() == 0)
				{
					configSheet = Def.DEFAULT_CONFIG;
				}
				ExcelConvert.readExcelFile(name, configSheet);
			}
			ExcelConvert.run();
		}
		catch(Exception e) 
		{
			e.printStackTrace();
			Common.print(e.toString());
		}
	}
}
